package com.example.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的内置过滤器
        /**
         *  anon:无需认证即可访问
         *  authc:必须认证才能访问
         *  user:必须拥有 记住我 功能才可以用
         *  perms:拥有对某个资源的权限才能访问
         *  role:拥有某个角色权限才能访问
         */
        Map<String, String> map = new LinkedHashMap<>();
        //map.put("/user/*","authc");假如拦截放在这行，那么下面的授权就不会生效了...迷~
        map.put("/user/update","perms[user:update]");//授权（ 假如第一次直接试图进入/user/update页面，会跳转到登录界面，而不会跳转到未授权页面）
        map.put("/user/add","perms[user:add]");
        map.put("/user/*","authc");//拦截（优先级：拦截>授权）

        bean.setFilterChainDefinitionMap(map);

        bean.setLoginUrl("/toLogin");//设置登录页面的路径
        bean.setUnauthorizedUrl("/unauth");//设置未授权跳转页面

        return bean;
    }
    //DefaultWebSecurityManger
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getUserRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    //realm
    @Bean
    public UserRealm getUserRealm(){
        return new UserRealm();
    }
    //整合ShiroDialect：用来整合Shiro+Thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
